<template>
  <div><!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/nav' }">组织管理</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/nav/roles">角色管理</a></el-breadcrumb-item>
    </el-breadcrumb>
  </div>
  <!-- 搜索 -->
  <div class="user-content">
    <div class="item">
      <el-input v-model="input" placeholder="请输入用户名或者手机号" />
      <button class="btn">搜索</button>
      <button class="btn1">重置</button>
    </div>
    <!-- 搜索下的按钮 -->
    <div class="newAdd">
      <button @click="dialog = true" class="addBtn">新增角色</button>
    </div>
    <!-- 新增角色弹出框 -->
    <el-drawer ref="drawerRef" v-model="dialog" title="新增角色" :before-close="handleClose" direction="rtl"
      class="demo-drawer">
      <div class="demo-drawer__content">
        <el-form :model="roleVo" :rules="rules1">
          <el-form-item label="角色名称" prop="name" :label-width="formLabelWidth">
            <el-input v-model="roleVo.role.name" autocomplete="off" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述" prop="describe" :label-width="formLabelWidth">
            <el-input v-model="roleVo.role.description" placeholder="请输入角色描述">
            </el-input>
          </el-form-item>
          <el-form-item label="权限选择" prop="choose" :label-width="formLabelWidth">
            <!-- <el-tree :data="data1" show-checkbox node-key="id" :props="defaultProps" /> -->
            <el-tree :data="data1" ref="mytree1" @change="myCurrent1" show-checkbox node-key="id"
              :default-expanded-keys="[]" :props="defaultProps" :default-checked-keys="form1.defaultPermTreeSelect" />
          </el-form-item>

        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">取消</el-button>
          <el-button type="primary" :loading="loading" @click="onClick1">{{
            loading ? '提交中' : '提交'
          }}</el-button>
        </div>
      </div>
    </el-drawer>
    <!-- 表格 -->
    <div class="list-item">
      <el-table :data="dataList" style="width: 100%">
        <el-table-column prop="name" label="用户名称" width="180" />
        <el-table-column prop="description" label="角色描述" width="180" />
        <el-table-column prop="perms" label="拥有的权限" width="180">
          <template #default="scoped">
            <div>{{ authList(scoped.row.perms) }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="time" label="创建时间" width="180" />
        <el-table-column label="操作">
          <template #default="scoped">
            <el-popconfirm @confirm="handleDelete(scoped.row)" title="您确定要删除吗?">
              <template #reference>
                <el-button type="danger" size="small">删除</el-button>

              </template>
            </el-popconfirm>

            <el-button size="small" type="primary" @click="edit(scoped.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

  </div>
  <!-- 编辑弹出框 -->
  <el-drawer ref="drawerRef2" v-model="dialog1" title="编辑角色" :before-close="handleClose1" direction="rtl"
    class="demo-drawer">
    <div class="demo-drawer__content">
      <el-form :model="form2" :rules="rules2">
        <el-form-item label="用户名称" prop="name" :label-width="formLabelWidth">
          <el-input v-model="form2.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="角色描述" prop="describe" :label-width="formLabelWidth">
          <el-input v-model="form2.describe">
          </el-input>
        </el-form-item>
        <el-form-item label="权限选择" prop="perms" :label-width="formLabelWidth">
          <!-- <el-tree :data="data1" show-checkbox node-key="id" :props="defaultProps" /> -->
          <el-tree v-if="dialog1" :data="data2" ref="mytree2" @change="myCurrent2"  show-checkbox node-key="id" :props="defaultProps"
            :default-checked-keys="form2.defaultPermTreeSelect" />
        </el-form-item>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button @click="cancelForm1">取消</el-button>
        <el-button type="primary" :loading="loading" @click="onClick2">{{
          loading ? '修改中' : '提交'
        }}</el-button>
      </div>
    </div>
  </el-drawer>
  <el-pagination background layout="prev, pager, next" :total="500" />
</template>

<!-- 
  默认展开的节点的 key 的数组
              :default-expanded-keys="[2, 2]"
              默认勾选的节点的 key 的数组
            :default-checked-keys="[5]"
 -->
<script lang='ts' setup>

import { onMounted, reactive, ref ,watch} from 'vue'
import { ElDrawer, ElMessageBox, FormRules, ElMessage } from 'element-plus'
import { roleApi, delRolesApi, addRolesApi, permsApi, updateApi } from "../../apis/roles.js"

const drawerRef = ref<InstanceType<typeof ElDrawer>>()
const drawerRef2 = ref<InstanceType<typeof ElDrawer>>()

const dataList = ref([])

const page = ref(1)
const size = ref(50)
let roleVo = reactive({
  role: {
    id:"",
    name: "",
    description: "",
  },
  ids: []
})

const input = ref('')

const defaultProps = {
  children: 'children',
  label: 'description',
}

//树形控件el-tree中的数据
// const data1 = [
//   {
//     id: 1,
//     label: '组织管理',}
//     children: [
//       {
//         id: 4,
//         label: '用户管理',
//         children: [
//           {
//             id: 9,
//             label: 'Level three 1-1-1',
//           },
//           {
//             id: 10,
//             label: 'Level three 1-1-2',
//           },
//         ],
//       },
//       {
//         id: 4,
//         label: '角色管理',
//       },
//       {
//         id: 4,
//         label: '菜单管理',
//       },
//     ],
//   },
//   {
//     id: 2,
//     label: '靶场管理',
//     children: [
//       {
//         id: 5,
//         label: 'Level two 2-1',
//       },
//       {
//         id: 6,
//         label: 'Level two 2-2',
//       },
//     ],
//   },
// ]
let data1: any = []
let data2: any = []

// 新增按钮获取input的值
const mytree1 = ref();
// 新增
const form1 = reactive({
  name: '',
  describe: '',
  defaultPermTreeSelect: []
})

// 新增
function myCurrent1() {
  // console.log(111);
  console.log(mytree1.value?.getCheckedNodes());
  form1.defaultPermTreeSelect = mytree1.value?.getCheckedNodes()

}
// 新增
const rules1 = reactive<FormRules>({
  name: { required: true, message: '请输入角色名称' },
  describe: { required: true, message: '请输入角色描述' },
})
// 新增按钮
const onClick1 = (val: any) => {

  drawerRef.value!.close()
  form1.defaultPermTreeSelect.forEach((item) => {
    roleVo.ids.push(item.id)
  })
  console.log(roleVo);
  addRolesApi(roleVo)
    .then((res: any) => {
      ElMessage.success("添加成功")
      getData()
      // 值清空
      roleVo.role.id = ""
      roleVo.role.name =""
      roleVo.role.description=""
      // form1.defaultPermTreeSelect=[]
    })

}

// 新增按钮弹出页面逻辑
const dialog = ref(false)
const handleClose = (done: any) => {
  if (loading.value) {
    return
  }
  ElMessageBox.confirm('是否确认提交?')
    .then(() => {
      loading.value = true
      timer = setTimeout(() => {
        done()
        // 动画关闭需要一定的时间
        setTimeout(() => {
          loading.value = false
        }, 400)
      }, 2000)
    })
    .catch(() => {
      // catch error
    })
}
// 新增角色弹出框---取消事件
const cancelForm = () => {
  loading.value = false
  dialog.value = false
  clearTimeout(timer)
}


// 编辑按钮获取input的值
const mytree2 = ref();
// 编辑
const form2 = reactive({
  id:"",
  name: '',
  describe: '',
  defaultPermTreeSelect: []
})
watch(form2 ,(newVal)=>{
  console.log("newVl",newVal)
})
// let currentNum = reactive({
//   name: '',
//   description: '',
//   perms:''
  
// })
// 编辑
function myCurrent2() {
  form2.defaultPermTreeSelect = mytree2.value?.getCheckedNodes()
}
// 编辑
const rules2 = reactive<FormRules>({
  name: { required: true, message: '请输入角色名称' },
  describe: { required: true, message: '请输入角色描述' },
})
// 编辑中的提交按钮
const onClick2 = (val: any) => {

  drawerRef2.value!.close()
  console.log(form2);
  roleVo.ids=[]
  form2.defaultPermTreeSelect.forEach((item:any)=>{
   
    roleVo.ids.push(item.$treeNodeId)
  })
console.log(form2.defaultPermTreeSelect);

  // roleVo.role.id=form2.id
  roleVo.role.name=form2.name
  roleVo.role.description=form2.describe
  // roleVo.ids=form2.defaultPermTreeSelect
  console.log(roleVo.ids);
  
  
  console.log(roleVo);
  updateApi(roleVo)
    .then((res: any) => {
      console.log(res);
      // ElMessage.success("修改成功")
      getData()

    })

}

// 编辑按钮弹出页面逻辑
const dialog1 = ref(false)
const handleClose1 = (done: any) => {
  if (loading.value) {
    return
  }
  ElMessageBox.confirm('是否确认提交?')
    .then(() => {
      form2.defaultPermTreeSelect = []
      loading.value = true
      timer = setTimeout(() => {
        done()
        // 动画关闭需要一定的时间
        setTimeout(() => {
          loading.value = false
        }, 400)
      }, 2000)
    })
    .catch(() => {
      // catch error
    })
}
// 编辑弹出框---取消事件
const cancelForm1 = () => {
  loading.value = false
  dialog1.value = false
  clearTimeout(timer)
}

// 编辑角色弹出框input中值的绑定
function edit(currentNum: any) {
  // form2.defaultPermTreeSelect = []
  console.log(currentNum);
  
  // console.log(form2);
  
  dialog1.value = true;
  roleVo.role.id = currentNum.id
  form2.name = currentNum.name;
  form2.describe = currentNum.description;
  form2.defaultPermTreeSelect = currentNum.perms.map((item: { id: any; }) => {
    return item.id
  })

}


const formLabelWidth = '100px'

let timer: any
const loading = ref(false)
// 删除
const drawer1 = ref(false)


function authList(list: any) {
  // console.log(list);
  const newList = list.map((item: { description: any; }) => {
    return item.description
  })
  // 将数组中的
  return newList.join(",")

}


interface DataType {
  key: string;
  roleName: string;//角色名称
  description?: string;//角色描述
  permissions: { permissionName: string; }[]//角色对应的权限列表
  createDate: string;//角色创建日期

}


onMounted(() => {

  // 查询所有角色
  getData()

  // 获取所有权限
  getPermsData()

})



// 查询所有角色
const getData = async () => {
  const data = { "page": page.value, "size": size.value }
  let res = await roleApi(data)
  console.log(res.data.data.data);
  dataList.value = res.data.data.data

}

// 获取所有权限
const getPermsData = async () => {
  let res = await permsApi()

  let obj = {
    id: 1,
    label: '拥有的权限',
    children: [],
  }
  obj.children = [...res.data.data]
  data1.push(obj)
  console.log(data1);
  // 将新增循环的数据data1复制给编辑循环的数据data2
  data2 = [...data1]

}

// 通过id删除
const handleDelete = (val: any) => {
  // console.log("2" + val.name);
  delRolesApi(val.id)
    .then((res: any) => {
      ElMessage.success("删除成功");
      getData()
    })

}



</script>

<style lang='less' scoped>
.user-content {
  width: 100%;
  min-height: 500px;
  margin-top: 20px;
  background-color: white;
  padding-top: 20px;
  padding-left: 20px;
  box-sizing: border-box;

  .item {
    margin-bottom: 20px;



    .btn1 {
      width: 80px;
      height: 40px;
      line-height: 40px;
      border: none;
      margin-left: 20px;
      border-radius: 4px;
    }

  }

  .el-input {
    width: 200px;
    height: 40px;
  }
}

.btn {
  width: 80px;
  height: 40px;
  line-height: 40px;
  border: none;
  background-color: #139DFF;
  color: aliceblue;
  margin-left: 20px;
  border-radius: 4px;
}

.addBtn {
  width: 80px;
  height: 40px;
  line-height: 40px;
  border: none;
  background-color: #139DFF;
  color: aliceblue;
  margin-left: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}
</style>